<?php
/**
 * Created by PhpStorm.
 *
 * Date: 2018/8/25
 * Time: 17:08
 */

namespace app\admin\controller;

use app\admin\model\Wallet;
use app\common\model\Commission;
use app\common\model\Member;
use app\common\model\Message;
use think\Exception;
use think\Db;

class User extends Common
{
    public function solveapply()
    {
        $id = input("id");
        $t = input("t");
        $remark = input("remark");
        $sheet = \db("card_apply")->where("id", $id)->find();
        if(!$sheet){
            $this->ajaxError("记录不存在");
        }
        if ($t == 1){
            //审核通过
            $data['status'] = 1;
        }else{
            //审核拒绝
            $data['status'] = 2;
            $data['remark'] = $remark;
        }
        $data['update_time'] = now_datetime();
        if(\db("card_apply")->where("id", $id)->update($data)){
            if($t == 1){
                \db('user')->where('id', $sheet['user_id'])->update([
                    'selfcard'=>$sheet['selfcard'],
                    'realname'=>$sheet['realname'],
                    'mustman'=>$sheet['mustman'],
                    'card_1'=>$sheet['card_1'],
                    'card_2'=>$sheet['card_2']
                ]);
            }
            $this->ajaxSuccess("处理完成");
        }else{
            $this->ajaxError("处理失败");
        }
    }
    
    
    /**
     * 实名记录
     */
    public function certification()
    {
        $param = input("get.");
        $model = \db("card_apply")->alias("a")->join("user b", "a.user_id=b.id")->field('a.id, a.user_id, a.selfcard, a.realname, a.status, b.username, a.card_1, a.card_2');
        if(isset($param["status"]) && !empty($param['status'])){
            $model->where("a.status", $param["status"]);
        }else{
            $param["status"] = "";
        }
        $list = $model->order("a.create_time desc")->paginate(10, false, ["query"=>$param]);
        $this->assign("param", $param);
        $this->assign("list", $list);
        return $this->fetch("certification");
    }
    /**
     * 工单列表
     */
    public function workSheet()
    {
        $param = input("get.");
        $model = \db("work_sheet");
        if(isset($param["status"]) && !empty($param["status"])){
            $model->where("status", $param["status"]);
        }else{
            $param["status"] = "";
        }
        if(isset($param["type"]) && !empty($param["type"])){
            $model->where("type", $param["type"]);
        }else{
            $param["type"] = "";
        }
        $list = $model->order("create_time desc")->paginate(10, false, ["query"=>$param]);
        $this->assign("param", $param);
        $this->assign("list", $list);
        return $this->fetch("work_sheet");
    }

    /**
     * 处理工单
     */
    public function solveworksheet()
    {
        $sheet_id = input("sheet_id");
        $sheet = \db("work_sheet")->where("id", $sheet_id)->find();
        if(!$sheet){
            $this->ajaxError("记录不存在");
        }
        $data['status'] = 2;
        $data['solve_time'] = now_datetime();
        if(\db("work_sheet")->where("id", $sheet_id)->update($data)){
            $this->ajaxSuccess("处理成功");
        }else{
            $this->ajaxError("处理失败");
        }



    }


    public function index()
    {
        //标题
        $this->templateTitle("会员列表");
        $where['us.id'] = ['gt', 0];

	    /*根据激活状态查看*/
	    $is_active = trim(request()->param("is_active"));
	    if ($is_active) {
	    	if($is_active!=1){
			    $where["us.is_active"] = 2;
		    }else{
			    $where["us.is_active"] = 1;
		    }
	    }
	    $this->assign("is_active", $is_active);

	    /*根据账号类型*/
	    $levelid = trim(request()->param("levelid"));
	    if ($levelid) {
	    	$where["us.levelid"] = $levelid;
	    }
	    $this->assign("levelid", $levelid);

	    /*根据等级筛选*/
	    $apply_open = trim(request()->param("apply_open"));
	    if ($apply_open) {
		    $where["us.is_our"] = $apply_open;
	    }
	    $this->assign("apply_open", $apply_open);

	    /*根据等级筛选*/
	    $is_levfix = trim(request()->param("is_levfix"));
	    if ($is_levfix) {
		    $where["us.is_levfix"] = $is_levfix;
	    }
	    $this->assign("is_levfix", $is_levfix);

	    //用户id
	    $uid =  trim(request()->param("uid"));
	    if(!empty($uid)){
		    $where['id'] = $uid;
	    }
	    $this->assign("uid", $uid);

        //搜索条件-手机
        $mobile = request()->param("selfphone");
        $this->assign("selfphone", $mobile);
        if ($mobile) {
            $where["us.selfphone"] = $mobile;
        }
        //搜索条件-姓名
        $nick_name = request()->param("username");
        $this->assign("username", $nick_name);
        if ($nick_name) {
            $where["us.username"] = ['like', "%$nick_name%"];
        }
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $where["us.realname"] = ['like', "%$realname%"];
	    }

	    /*所有以及类型*/
	    $list_cate = \db('Userlevel')->where("pid=0 and zt=1")->order("sort desc,id desc")->select();
	    $this->assign("catelist", $list_cate);
	    $new_level = [];
	    foreach($list_cate as $v){
		    $new_level[$v['id']] = $v['title'];
	    }
        //获取所有用户
        $list = Db::name("user")
            ->alias('us')
            ->where($where)
            ->order("us.id ASC")
            ->paginate(10);
	       $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {
			    $table = config('db_order_table');
			    $list['data'][$k]['salenums'] = Db::name($table)->where("buyuid='".$v['id']."'")->sum('price');
			    $list['data'][$k]['buynums'] =  Db::name($table)->where("peiduiuid='".$v['id']."'")->sum('basicprice');
			    $list['data'][$k]['catetitle'] = $new_level[$v['levelid']];
		    }
	    }
        $this->assign("list", $list);
	    $this->assign("page", $page);
        return $this->fetch();
    }

    /**
     * 会员钱包
     */
    public function wallet()
    {
	    //标题
	    $this->templateTitle("会员钱包");
	    $where['us.id'] = ['gt', 0];

	    /*根据激活状态查看*/
	    $is_active = trim(request()->param("is_active"));
	    if ($is_active) {
		    if($is_active!=1){
			    $where["us.is_active"] = 0;
		    }else{
			    $where["us.is_active"] = 1;
		    }
	    }
	    $this->assign("is_active", $is_active);

	    //搜索条件-手机
	    $mobile = request()->param("selfphone");
	    $this->assign("selfphone", $mobile);
	    if ($mobile) {
		    $where["us.selfphone"] = $mobile;
	    }
	    //搜索条件-姓名
	    $nick_name = request()->param("username");
	    $this->assign("username", $nick_name);
	    if ($nick_name) {
		    $where["us.username"] = ['like', "%$nick_name%"];
	    }
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $where["us.realname"] = ['like', "%$realname%"];
	    }

	    //获取所有用户
	    $list = Db::name("user")
		    ->alias('us')
		    ->where($where)
		    ->order("us.id ASC")
		    ->paginate(10);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {
			    $table = config('db_order_table');
			    $list['data'][$k]['salenums'] = Db::name($table)->where("buyuid='".$v['id']."'")->sum('price');
			    $list['data'][$k]['buynums'] =  Db::name($table)->where("peiduiuid='".$v['id']."'")->sum('basicprice');
		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }
	/**
	 * 编辑钱包
	 */
    public function edit_money(){
	    $id = request()->param('id');
	    if (request()->isGet()) {
		    $this->layoutModal();
		    $info = Db::name('user')->where('id', $id)->find();
		    $this->assign('info', $info);
		    return $this->fetch();
	    }
    }
	/*修改合约收益*/
	public function editprofit(){
		if(request()->isPost()){
			$myprofit = intval($_POST['myprofit']);
			$id = intval($_POST['id']);
			$user_have = Db::name('User')->where("id=".$id)->field('myprofit')->find();
			$user_have = $user_have['myprofit'];
			if($myprofit<=0){
				$this->ajaxError('合约收益数量不能小于0');
			}
			$isadd = intval($_POST['isadd']);
			if($isadd<=0 || $isadd>=3){
				$this->ajaxError('非法操作');
			}
			/*减少的话，看余额是否充足*/
			if($isadd==2){
				if($myprofit > $user_have){
					$this->ajaxError('合约收益余额不足');
				}
			}
			$addsuc = $isadd==1?'管理员新增合约收益':"管理员减少合约收益";

			$data['uid'] = $_POST['id'];
			$data['orderid'] = 0;
			$data['earnmoney'] = $myprofit;
			$data['dotime'] = date('Ymd');
			$data['isadd'] = $isadd;
			$data['status'] = 2;
			$data['ctime'] = time();
			$data['sendtime'] = time();
			$data['info'] = $addsuc;
			$insertid = Db::name('orderearn')->insertGetId($data);
			if($insertid>0){
				if($isadd==1){
					Db::name('User')->where("id='".$_POST['id']."'")->setInc('myprofit',$myprofit);
				}
				if($isadd==2){
					Db::name('User')->where("id='".$_POST['id']."'")->setDec('myprofit',$myprofit);
				}
				$this->ajaxSuccess($addsuc);
			}else{
				$this->ajaxError('系统繁忙，请稍后再试！');
			}
		}
	}
	/*共享豆修改*/
	public function editpoints(){
		if(request()->isPost()){
			$integral = intval($_POST['integral']);
			$user_have = Db::name('User')->where("id='".intval($_POST['id'])."'")->field('integral')->find();
			$user_have = $user_have['integral'];
			if($integral<=0){
				$this->ajaxError('共享豆数量不能小于0');
			}
			$isadd = intval($_POST['isadd']);
			if($isadd<=0 || $isadd>=3){
				$this->ajaxError('非法操作！');
			}
			/*减少的话，看余额是否充足*/
			if($isadd==2){
				if($integral > $user_have){
					$this->ajaxError('共享豆余额不足！');
				}
			}
			$addsuc = $isadd==1?'新增共享豆':"减少共享豆";
			$insertid = points_his($_POST['id'],$isadd,$integral,0,'管理员'.$addsuc);
			if($insertid>0){
				if($isadd==1){
					Db::name('User')->where("id='".$_POST['id']."'")->setInc('integral',$integral);
				}
				if($isadd==2){
					Db::name('User')->where("id='".$_POST['id']."'")->setDec('integral',$integral);
				}
				$this->ajaxSuccess($addsuc);
			}else{
				$this->ajaxError('系统繁忙，请稍后再试！');
			}
		}

	}
	/*ATC修改：2018-12-18 13:55*/
	public function editwages(){
		if(request()->isPost()){
			$wagesall = intval($_POST['wagesall']);
			$user_have = Db::name('User')->where("id='".intval($_POST['id'])."'")->field('wagesall')->find();
			$user_have = $user_have['wagesall'];
			if($wagesall<=0){
				$this->ajaxError('团队奖数量不能小于0');
			}
			$isadd = intval($_POST['isadd']);
			if($isadd<=0 || $isadd>=3){
				$this->ajaxError('非法操作！');
			}
			/*减少的话，看余额是否充足*/
			if($isadd==2){
				if($wagesall > $user_have){
					$this->ajaxError('团队奖余额不足！');
				}
			}
			$addsuc = $isadd==1?'新增团队奖':"减少团队奖";
			$insertid = wages_his($_POST['id'],$isadd,$wagesall,0,'管理员'.$addsuc);
			if($insertid>0){
				if($isadd==1){
					Db::name('User')->where("id='".$_POST['id']."'")->setInc('wagesall',$wagesall);
				}
				if($isadd==2){
					Db::name('User')->where("id='".$_POST['id']."'")->setDec('wagesall',$wagesall);
				}
				$this->ajaxSuccess($addsuc);
			}else{
				$this->ajaxError('系统繁忙，请稍后再试！');
			}
		}

	}
	/*直推奖励修改*/
	public function editpushs(){
		if(request()->isPost()){
			$pushs = intval($_POST['pushs']);
			$user_have = Db::name('User')->where("id='".intval($_POST['id'])."'")->field('pushs')->find();
			$user_have = $user_have['pushs'];
			if($pushs<=0){
				$this->ajaxError('推广收益数量不能小于0');
			}
			$isadd = intval($_POST['isadd']);
			if($isadd<=0 || $isadd>=3){
				$this->ajaxError('非法操作！');
			}
			/*减少的话，看余额是否充足*/
			if($isadd==2){
				if($pushs > $user_have){
					$this->ajaxError('推广收益余额不足！');
				}
			}
			$addsuc = $isadd==1?'新增推广收益':"减少推广收益";
			$insertid = pushs_his($_POST['id'],$isadd,$pushs,0,'管理员操作');
			if($insertid>0){
				if($isadd==1){
					Db::name('User')->where("id='".$_POST['id']."'")->setInc('pushs',$pushs);
				}
				if($isadd==2){
					Db::name('User')->where("id='".$_POST['id']."'")->setDec('pushs',$pushs);
				}
				$this->ajaxSuccess($addsuc);
			}else{
				$this->ajaxError('系统繁忙，请稍后再试！');
			}
		}
	}

    /**
     * 团队关系
     */
    public function team()
    {
	    $this->assign("user_id", 0);
    	return $this->fetch();
    }


    /**
     * 我的SCB值
     */
    public function mybot()
    {
	    $where['us.id'] = ['gt', 0];
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("mybot")
		    ->alias('us')
		    ->where($where)
		    ->order("us.id DESC")
		    ->paginate(18);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }
    /*SCB 值修改*/
	public function editmybot(){
		if(request()->isPost()){
			$integral = round($_POST['mybot'],2);
			$user_have = Db::name('User')->where("id='".intval($_POST['id'])."'")->field('mybot')->find();
			$user_have = $user_have['mybot'];
			if($integral<=0){
				$this->ajaxError('SCB数量不能小于0');
			}
			$isadd = intval($_POST['isadd']);
			if($isadd<=0 || $isadd>=3){
				$this->ajaxError('非法操作！');
			}
			/*减少的话，看余额是否充足*/
			if($isadd==2){
				if($integral > $user_have){
					$this->ajaxError('SCB余额不足！');
				}
			}
			$addsuc = $isadd==1?'新增SCB':"减少SCB";
			$insertid = mybot_his($_POST['id'],$isadd,$integral,0,'管理员'.$addsuc);
			if($insertid>0){
				if($isadd==1){
					Db::name('User')->where("id='".$_POST['id']."'")->setInc('mybot',$integral);
				}
				if($isadd==2){
					Db::name('User')->where("id='".$_POST['id']."'")->setDec('mybot',$integral);
				}
				$this->ajaxSuccess($addsuc);
			}else{
				$this->ajaxError('系统繁忙，请稍后再试！');
			}
		}
	}



    /**
     * 合约收益
     */
    public function earnings()
    {
	    $where['us.id'] = ['gt', 0];
	    $where['us.status']=2;
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("orderearn")
		    ->alias('us')
		    ->where($where)
		    ->order("us.sendtime desc,us.id DESC")
		    ->paginate(18);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }

    /**
     * 共享豆记录
     */
    public function scoreList()
    {
	    $where['us.id'] = ['gt', 0];
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("points")
		    ->alias('us')
		    ->where($where)
		    ->order("us.id DESC")
		    ->paginate(18);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }

    /**
     * ATC记录
     */
    public function atcList()
    {
	    $where['us.id'] = ['gt', 0];
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("wages")
		    ->alias('us')
		    ->where($where)
		    ->order("us.id DESC")
		    ->paginate(18);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }

    /**
     * 推广收益
     */
    public function spreadEarnings()
    {
	    $where['us.id'] = ['gt', 0];
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("pushslist")
		    ->alias('us')
		    ->where($where)
		    ->order("us.id DESC")
		    ->paginate(18);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }

    /**
     * 会员投诉
     */
    public function complain()
    {
	    $where['us.id'] = ['gt', 0];
	    //搜索条件-真实姓名
	    $realname = request()->param("realname");
	    $this->assign("realname", $realname);
	    if ($realname) {
		    $uid = get_uid($realname);
		    $where["us.uid"] = ['in', $uid];
	    }
	    //获取所有用户
	    $list = Db::name("complain")
		    ->alias('us')
		    ->where($where)
		    ->order("status asc,us.id DESC")
		    ->paginate(15);
	    $page = $list->render();
	    $list=$list->toArray();
	    if (! empty($list)) {
		    foreach ($list['data'] as $k => $v) {

		    }
	    }
	    $this->assign("list", $list);
	    $this->assign("page", $page);
	    return $this->fetch();
    }

	/*修改状态*/
	public function changestatus(){
		if (request()->isAjax()) {
			$id = intval(request()->param("id"));
			$data['status'] =request()->param("status");
			$do =  Db::name('complain')->where("id=".$id)->update($data);

			if($do){
				/*操作日志*/
				Message::admin_log(0, "会员投诉处理！");
				return $this->ajaxSuccess('设置成功！');
			}else{
				return $this->ajaxError('设置失败!');

			}
		}
	}

	/*删除会员*/
    public function delete(){
	    if (request()->isAjax()) {
		    $id = request()->param("id");
		    try {
			    $userxx = Db::name("user")->where('id',$id)->find();
			    $user_next_num = Db::name("user")->where('pid',$id)->count();
			    if($user_next_num>=1){
				    return $this->ajaxError('此用户有下级'.$user_next_num.'人，无法删除！');
			    }
			    if ($id<>'' && $userxx['username']<>''){
				    Db::name("user")->where(array('id' => $id))->delete();
				    /*--x递归修改这个人所有上级，让团队人数减一--*/
				    del_team($userxx['recommend']);
				    /*操作日志*/
				    Message::admin_log(0, "删除会员,id：".$userxx['id'].'-用户名:'.$userxx['username'].'('.$userxx['selfphone'].')');
				    return $this->ajaxSuccess('操作成功！');
			    }else {
				    return $this->ajaxError('公司账号不能删除!');
			    }
		    } catch (Exception $exception) {
			    $this->ajaxError($exception->getMessage());
		    }

	    }
    }
    /* 重置密码*/
	public function usermb(){
		if (request()->isAjax()) {
			$id = request()->param("id");
			try {
				$userxx = Db::name("user")->where('id',$id)->find();
				if ($id<>'' && $userxx['username']<>''){
					$do = Db::name("user")
						->where(array('id' => $id))
						->update(array(
							'passwd'=>md5(md5('123456'))
						));
					if($do){
						/*操作日志*/
						Message::admin_log(0, "后台重置会员(".$userxx['username'].")登录密码！");
						return $this->ajaxSuccess('操作成功！');
					}else{
						return $this->ajaxSuccess('密码已经是123456！');
					}
				}else {
					return $this->ajaxError('用户不存在!');
				}
			} catch (Exception $exception) {
				$this->ajaxError($exception->getMessage());
			}

		}
	}
	/*登录前台用户*/
	function loginadmin(){
		/*给前台session，并登录后跳转*/
		$id=request()->param("id");
		$user= Db::name("user")->where(" id='".$id."' ")->find();
		session('user_id',$user['id']);
		$id_last = Message::admin_log(0,"登录会员".$user['username']);
		$_SESSION['logintime'] = time();
		$_SESSION['last_loginid'] = $id_last;
		$now_root = "http://".$_SERVER['HTTP_HOST'].'/';
		header("location:$now_root");exit;
	}
    /*修改会员信息*/
    public function edit()
    {
        $id = request()->param('id');
        if (request()->isGet()) {
            $this->layoutModal();
            $info = Db::name('user')->where('id', $id)->find();
	        $info['tui_selfphone'] = '无';
            if(!empty($info['pid'])){
	            $tuiinfo = Db::name('user')->where("id =".$info['pid'])->field('selfphone')->find();
	            $info['tui_selfphone'] = $tuiinfo['selfphone'];
            }

            $this->assign('info', $info);
	        /*所有以及类型*/
	        $list_cate = \db('Userlevel')->where("pid=0 and zt=1")->order("sort desc,id desc")->select();
	        $this->assign("catelist", $list_cate);
            return $this->fetch();
        }
	    if (request()->isAjax()) {
		    $where['id'] = $id;
	        $user = \db("user")->where("id", $id)->find();
	        $user_status = $user['user_status'];
	        $data = $_POST;
		    if(!verify_mobile($data['selfphone'])){
			    $this->ajaxError('手机号格式不正确');
		    }
		    $id =  Db::name('user')->where("id !=".$id." and selfphone='".$data['selfphone']."'")->field('id')->find();
		    if(!empty($id)){
			    $this->ajaxError('手机号已被注册');
		    }
		    if(!empty($data['sepasswd'])){
			    $data['sepasswd'] = md5(md5($data['sepasswd']));
		    }else{
		    	unset($data['sepasswd']);
		    }
		    try {
		    	//如果身份证号和真实姓名不能为空，那么就记录到实名认证表里面
		    	if(!empty($data['realname']) && !empty($data['selfcard'])){
		    		//查一下有没有
		    		$is_card_do = Db::name('card_apply')->where("user_id='".$where['id']."'")->find();
		    		if(!empty($is_card_do)){
		    			$card_update = ['realname'=>$data['realname'],'selfcard'=>$data['selfcard']];
		    			Db::name('card_apply')->where("user_id='".$where['id']."'")->update($card_update);
		    		}else{
		    			Db::name('card_apply')->insert([
		                    'user_id'=>$where['id'],
		                    'realname'=>$data['realname'],
		                    'selfcard'=>$data['selfcard'],
		                    'status'=>1,
		                    'create_time'=>time()
		                ]);
		    		}
		    	}


			    $save = Db::name('user')->where($where)->update($data);
			    if ($save) {
			        //是否激活会员
			        if($data['user_status']!=$user_status && $data['user_status'] == 1){
                        /*====给上一级的直推人数加1，以及上一级的每一个人团队人数加一======start===*/
                        //先找到上一级的id，以及上一级的全部路径
                        $this_active_parentid = $user['pid'];
                        if(!empty($this_active_parentid)){
                            $myupinfo = \db('user')->where("id='".$this_active_parentid."'")->field('id,pid,pidcount,recommend,teamcount')->find();
                            //先给上一级直推人数加一
                            \db('user')->where("id='".$this_active_parentid."'")->setInc('pidcount');
                            $ary_up = excommend($user['recommend']);
                            /*再给每一个上一级团队人数加1*/
                            foreach($ary_up as $teamv){
                                \db('user')->where("id='".$teamv."'")->setInc('teamcount');
                                //检测每一个人当前级别，检测到了就存进去
                                $thislev = \db('user')->where("id='".$teamv."'")->field('id,pidcount,teamcount,pushs,is_levfix')->find();
                                if($thislev['is_levfix']!=2){
                                    //查询出售的收益
                                    $now_point_str = "uid='".$thislev['id']."' and isadd=2 and info='资产出售'";
                                    $now_user_points = \db("Pushslist")->where($now_point_str)->sum('nums');
                                    $now_user_points = empty($now_user_points)?0:$now_user_points;
                                    $thislev['pushs'] = ($thislev['pushs']+$now_user_points);
                                    if($thislev['pidcount']>=config('team_config.level_4')['pidcount'] && $thislev['teamcount']>=config('team_config.level_4')['teamcount'] && $thislev['pushs']>=config('team_config.level_4')['pushs']){
                                        $thisdata['levelid'] = 4;//三级代理
                                    }else if($thislev['pidcount']>=config('team_config.level_3')['pidcount'] && $thislev['teamcount']>=config('team_config.level_3')['teamcount'] && $thislev['pushs']>=config('team_config.level_3')['pushs']){
                                        $thisdata['levelid'] = 3;//二级代理
                                    }else if($thislev['pidcount']>=config('team_config.level_2')['pidcount'] && $thislev['teamcount']>=config('team_config.level_2')['teamcount'] && $thislev['pushs']>=config('team_config.level_2')['pushs']){
                                        $thisdata['levelid'] = 2;//一级代理
                                    }else{
                                        $thisdata['levelid'] = 1;//普通会员
                                    }
                                    \db('User')->where("id='".$teamv."'")->update($thisdata);
                                }
                            }
                        }
                        /*====给上一级的直推人数加1，以及上一级的每一个人团队人数加一======end===*/
                    }
				    /*操作日志*/
				    Message::admin_log(0, "会员(".$user['id']."-".$user['username'].")编辑成功！");
				    $this->ajaxSuccess('会员编辑成功');
			    } else {
				    $this->ajaxError('数据库繁忙，添加失败');
			    }
		    } catch (\Exception $exception) {
			    $this->ajaxError($exception->getMessage());
		    }
	    }
    }

    /*添加会员*/
    public function add()
    {
        if (request()->isGet()) {
	        /*所有以及类型*/
	        $list_cate = \db('Userlevel')->where("pid=0 and zt=1")->order("sort desc,id desc")->select();
	        $this->assign("catelist", $list_cate);
            $this->layoutModal();
            return $this->fetch();
        }
        if (request()->isAjax()) {
            $data = $_POST;
	        $id2 = Db::name('user')->where("username='".$data['username']."'")->field('id')->find();
	        if(!empty($id2)){
		        $this->ajaxError('用户名已被注册');
	        }
	        if(!verify_mobile($data['selfphone'])){
		        $this->ajaxError('手机号格式不正确');
	        }
	        $id =  Db::name('user')->where("selfphone='".$data['selfphone']."'")->field('id')->find();
	        if(!empty($id)){
		        $this->ajaxError('手机号已被注册');
	        }
	        $data['passwd'] = md5(md5($data['passwd']));
	        $data['sepasswd'] = md5(md5($data['sepasswd']));
	        $data['recommend'] = trim($data['recommend']);
	        if(!empty($data['recommend'])){
		        $uname =  Db::name('user')->where("selfphone='".$data['recommend']."' or username='".$data['recommend']."'")->field('recommend,id,rank')->find();
		        if(empty($uname)){
			        $this->ajaxError('没有此推荐人');
		        }else{
			        $data['recommend'] = $uname['recommend'].','.$uname['id'].',';
			        $data['pid'] = $uname['id'];
			        $data['rank'] = $uname['rank']+1;
		        }
	        }
            $data['regtime'] = date('Y-m-d H:i:s');
            $data['invite_code'] = getInviteCode();
            try {
                $id =  Db::name('user')->insertGetId($data);
                if ($id) {
	                /*操作日志*/
	                Message::admin_log(0, "会员".$data['username'].",手机号".$data['selfphone']."添加成功");
                    $this->ajaxSuccess('会员添加成功');
                } else {
                    $this->ajaxError('数据库繁忙，添加失败');
                }
            } catch (\Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }
        }
    }
	/*第一个加载的方法*/
	public function getTree() {
		if(request()->param("user1")!='0'){
			$getuser = request()->param("user1");
			$getuser = Db::name('user')->where("username='".$getuser."' or selfphone='".$getuser."'")->field('id')->find();
			$getuser  = $getuser['id'];
			if(empty($getuser)){
				$getuser = 1;
			}
		}else{
			$getuser = '1';
		}
		//echo json_encode ( array ("status" => 1,"data" => $getuser ) );die;
		$base = $this->getTreeBaseInfo ( $getuser );
		$znote = $this->getTreeInfo ($getuser);
		$znote [] = $base;
		echo json_encode ( array ("status" => 0,"data" => $znote ) );
	}
	/*用到的第二个方法*/
	public function getTreeBaseInfo($id) {
		if (! $id){
			return;
		}
		$r = Db::name("user")->where(array('id'=>$id))->find();
		if($r){
			$active_str = $r['is_active']==1?'-已激活':"-未激活";
			$user_statu = $r['user_status']==1?'--已转账激活':"-未转账激活";
			$user_str = $r['username']." - ".$r['selfphone'].' - '.$active_str.$user_statu;
			return array (
				"id" => $r ['id'],
				"pId" => $r ['pid'],
				"name" => $user_str
			);
		}
		return;
	}
	/*第三个加载的方法*/
	public function getTreeInfo($id) {
		static $trees = array ();
		$ids = self::get_childs ( $id );
		if (! $ids){
			return $trees;
		}
		$_SESSION['user_jb']++;
		foreach($ids as $v){
			$trees [] = $this->getTreeBaseInfo ( $v );
			$this->getTreeInfo ( $v );
		}
		return $trees;
	}
	/*第四个加载的方法*/
	public static function get_childs($id) {
		if(!$id){
			return null;
		}
		$childs_id = array();
		$childs = Db::name("user")->field("id")->where(array('pid'=>$id))->select();

		foreach ( $childs as $v ) {
			$childs_id [] = $v['id'];
		}

		if ($childs_id)
			return $childs_id;
		return 0;
	}
	/*第五个方法：搜索某个用户，调用的方法*/
	public function getTreeso(){
		if(request()->param("user")<>''){
			if(! preg_match ( '/^[a-zA-Z0-9@.]{1,120}$/',request()->param("user") )){
				echo json_encode ( array ("status" => 1,"data" => '用戶名格式不對!' ) );
			}else{
				$getuser = request()->param("user");
				$getuser = Db::name('user')->where("username='".$getuser."' or selfphone='".$getuser."'")->field('id')->find();
				if(empty($getuser)){
					echo json_encode ( array ("status" => 1,"data" => '用戶不存在!' ) );
				}else{
					$base = $this->getTreeBaseInfo($getuser['id']);
					$znote = $this->getTreeInfo($getuser['id']);
					$znote [] = $base;
					echo json_encode ( array ("status" => 0,"data" => $znote ) );
				}
			}
		}else{
			$base = $this->getTreeBaseInfo ('1');
			$znote = $this->getTreeInfo ('1');
			$znote [] = $base;
			echo json_encode ( array ("status" => 0,"data" => $znote ) );
		}
	}

}
